<template>
  <div style="height: 600px;overflow-y: auto;">
     <!--header-->
  <div class="pt-header">
    <h1 class="header-logo"><a href="#" title="猴趣乐">LOGO</a> </h1>  
  </div>
    <div class="editor_head" v-show="goods.length">
      <van-icon :name="isEditor ? 'success' : 'editor'" />
      <span @click="isEditor = !isEditor">{{isEditor ? '完成' : '编辑'}}</span>
    </div>


    <van-checkbox-group class="card-goods" v-model="checkedGoods">
    <div v-for="(item, i) in goods" class="card-goods__item">
      <van-checkbox
        :key="item.id"
        :name="item.id"
        :disabled="!item.status"
      >
      </van-checkbox>
      <van-card
          :title="item.name"
          :desc="item.desc"
          :num="item.num"
          :price="item.price"
          :thumb="item.img"
      />
      <div class="footer" slot="footer" >
        <van-stepper v-model="item.num" @change="numchange" />
      </div>
      </van-card>
      <div class="cart_delete" v-if="isEditor" @click="deleteCart(i)">删除</div>
     </div>
    </van-checkbox-group>




      <div class="clear_invalid" v-if="goods.length" @click="clearInvalid">
      <van-icon name="lajitong"/>
      清除失效商品
    </div>
    
   <is-empty v-if="!goods.length && isLogin">
     <span>您的购物车空空如也~</span>
   </is-empty>
   <is-empty v-if="!isLogin">
     <span>登陆后才能查看商品哦~</span><br />
     <van-button size="normal" @click="tologin" style="color:#999;">请登陆</van-button>
   </is-empty>
   


    <van-submit-bar
      :price="totalPrice"
      :disabled="!checkedGoods.length"
      :button-text="submitBarText"
      :loading="isSubmit"
      label="总计"
      @submit="onSubmit"
    >
    <van-checkbox v-model="checkedAll" @change="setCheckAll" style="padding: 0 10px;">
    全选
    </van-checkbox>

    </van-submit-bar>

  </div>
</template>

<script>
import { 
    Checkbox, 
    CheckboxGroup,
     Card, 
     SubmitBar, 
     Toast,
     Stepper,
     } from 'vant'

import isEmpty from './common/is-empty.vue'
export default {
  components: {
    [isEmpty.name]: isEmpty,
    [Card.name]: Card,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [CheckboxGroup.name]: CheckboxGroup
  },
  data() {
    return {
      isLogin: false,
      isSubmit: false,
      checkedAll: false,
      isEditor: false,
      checkedGoods: [],
      goods: []
    };
  },
   mounted(){
    this.$nextTick(function() {
        this.id = this.$route.params.id;
        this.initData();
      });
  },
  activated(){
      this.checkedAll = false;
      this.isEditor = false;
      this.isSubmit = false;
    },
  computed: {

    submitBarText() {
      const count = this.checkedGoods.length;
      return this.isEditor ? "删除" : '结算' + (count ? `(${count})` : '');
    },
    totalPrice() {
      return this.goods.reduce((total, item) => total + (this.checkedGoods.indexOf(item.id) !== -1 ? item.price * item.num : 0)*100, 0);
    }
  },
  methods: {
    numchange(numchange){
      var cartpath=localStorage["goodscart"];
      var cid;
      if(cartpath){
          cartpath = JSON.parse(cartpath);
          for (var i = 0; i < cartpath.length; i++){
            if(cartpath[i].num != this.goods[i].num){
              cid = this.goods[i].id;
              localStorage.setItem("goodscart",JSON.stringify(this.goods)); 
            }
          }
       }
       if(cid){
       this.$http
          .post(`/cart/update`,{id:cid,num:numchange})
          .then(res => {
            if (res.code == 200) {
                                             
            } else {
              this.$router.replace('/404')
            }
          })
          .catch(function(error) {});
       }
    },
    initData() {
        this.$http
          .get(`/cart/get`)
          .then(res => {
            if (res.code == 200) {
                this.isLogin = true;
                this.goods= res.result;  
                localStorage.setItem("goodscart",JSON.stringify(res.result));                          
            } else {
              this.$router.replace('/404')
            }
          })
          .catch(function(error) {});
      },
    tologin(){
    localStorage.setItem("loginpath","../cart");
     this.$router.push('../login');
    },
    
    onSubmit() {
      if(this.isEditor){
          this.$dialog.confirm({message: "确定删除所选商品吗?", cancelButtonText: "再想想"}).then(() => {
            this.goods = this.goods.filter( goods => (this.checkedGoods.indexOf(goods.id) == -1));
            this.checkedGoods = [];
            this.checkedAll = false;
            this.isEditor = !this.goods.length;
            localStorage.setItem("goodscart",JSON.stringify(this.goods));
          })
        }else{
          var goodsnew =[];
           for (var i = 0; i < this.checkedGoods.length; i++){
              for (var j = 0; j < this.goods.length; j++){
                if(this.checkedGoods[i] == this.goods[j].id){
                  goodsnew.push(this.goods[j])
                }
              }
           }

          localStorage.setItem("goodsnew",JSON.stringify(goodsnew));
          this.isSubmit = true;
          this.$router.push('../placeOrderEntity');
        }
      
    },
    clearInvalid(){
        this.$dialog.confirm({message: "确定清除所有失效商品吗?", cancelButtonText: "再想想"}).then(() => {
          this.goods = this.goods.filter(goods => goods.status)
        });
        localStorage.setItem("goodscart",JSON.stringify(this.goods));
      },
      setCheckAll(val){
        this.checkedGoods = val ? this.goods.filter(goods => !!goods.status).map(goods => goods.id) : [];
      },
    deleteCart(i){
        this.$dialog.confirm({message: "确定删除所选商品吗", cancelButtonText: "再想想"}).then(() => {
          let cartId = this.goods.splice(i, 1)[0].id;
          this.$nextTick(() => {
            this.deleteNext(cartId);
            localStorage.setItem("goodscart",JSON.stringify(this.goods));
          })
        })
      },
      deleteNext(cartId){
        this.$http
          .post(`/cart/del`,{id:cartId})
          .then(res => {
            if (res.code == 200) {
                                             
            } else {
              this.$router.replace('/404')
            }
          })
          .catch(function(error) {});
        this.isEditor = !!this.goods.length;
        this.checkedGoods.forEach((goods, i) => {
          if(goods.id == cartId){
            this.checkedGoods.splice(i, 1);
            return false;
          }
        })
      },
  }
};
</script>

<style lang="less">
.pt-header {
   min-height: 44px;
  height: 44px; 
  line-height: 40px;  
  position: relative; 
  background-color: #fff; 
  overflow: hidden; 
  }
  .header-logo { position: absolute; left: 1rem; bottom: .7rem; background-size: 180px 180px; background-position: 0 -142px; height: 28px; width: 260px;}
  .header-logo a { 
  display: inline-block; 
  background-size: 16rem 16rem;
  background-position: 0 -7.6rem;
  height: 100%; 
  width: 17rem; 
  text-indent: -9999px;
  background: url(/static/logo1.png) no-repeat; 
  }
.card-goods {
  padding: 10px 0;
  background-color: #fff;
  &__item {
    display: -webkit-box;
    display: -webkit-flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    margin-bottom: 10px;
    background-color: #fff;
    position: relative;
    background-color: #fafafa;
    .van-checkbox__label {
      width: 100%;
      padding: 0 10px 0 15px;
      box-sizing: border-box;
    }
    .van-checkbox__icon {
      top: 50%;
      left: 10px;
      z-index: 1;
      position: absolute;
      margin-top: -10px;
    }
    .van-card:not(:first-child) {
    width: 100%;
    margin-top: 0;
    padding-top: 10px;
    padding-bottom: 10px;
    }
    .van-card__price {
      color: #f44;
    }
    .van-checkbox{ 
      width:30px;
      height:21px;
      padding-left: 10px;
      box-sizing: border-box;
    }
    .footer{
      font-size: 12px;
      color: #999;
      right: 15px;
      bottom: 5px;
      position: absolute;
      width: 100%;
     padding-left: 170px;
     box-sizing: border-box;
    }
    .cart_delete{
      width:70px;
      height: 100px;
      line-height: 100px;
      padding: 0 10px;
      color: #fff;
      background-color: #db3d3c;
    }
  }
}
.van-submit-bar{
      bottom: 53px;
}
.editor_head{
    @include one-border;
    text-align: right;
    padding: 10px;
    font-size: 14px;
    background-color: #fff;
  }
  .clear_invalid{
    width: 120px;
    color: #999;
    border: 1px solid #999;
    margin: 0 auto;
    text-align: center;
    padding: 5px 3px;
    margin-top: 20px;
    border-radius: 3px;
  }
</style>